using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace Zero.Dialogue
{
    [Serializable]
    public class DialogueBehaviour : PlayableBehaviour
    {
        [Tooltip("角色名")]
        public string characterName;
        [Tooltip("对话框内容"), TextArea]
        public string body;
        [Tooltip("是否在片段播放完暂停")]
        public bool hasToPause = false;

        private bool _clipPlayed = false; // 片段是否播放过
        private bool _pauseScheduled = false; // 是否进行暂停
        private PlayableDirector _director; // 当前Timeline的播放器

        public override void OnPlayableCreate(Playable playable)
        {
            _director = playable.GetGraph().GetResolver() as PlayableDirector;
        }

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            if (!_clipPlayed
                && info.weight > 0f)
            {
                // 显示对话框
                DialogueSystem.Instance.ShowDialogueText(characterName, body);

                if (Application.isPlaying)
                {
                    if (hasToPause)
                    {
                        _pauseScheduled = true;
                    }
                }

                _clipPlayed = true;
            }
        }

        public override void OnBehaviourPause(Playable playable, FrameData info)
        {
            if (_pauseScheduled)
            {
                _pauseScheduled = false;
                // 暂停timeline
                _director.Pause();
            }
            else
            {
                // 关闭对话框
                DialogueSystem.Instance.HideDialogue();
            }
        }
    }
}